<?php

namespace App\Http\Controllers;

use App\Http\Models\Article;

use App\Http\Models\Category;
use Illuminate\Http\Request;

/**
 * 内容管理
 * Class ArticleController
 * @package App\Http\Controllers
 */
class ArticleController extends Controller
{
    /**
     * 文章列表
     */
    public function list(Request $request){
        # 查询数据
        # 分类名称 两表关联
        # 分类信息 动态展示以及保留搜索多条件进行分页、搜索高亮替换
        $category = Category::get();

        # 添加列表的搜索条件
        $category_id = $request->get('article_category_id',0);
        $where = [];
        if ($category_id > 0) {
            $where[] = ["category_id","=",$category_id];
        }

        $title = $request->get('title');
        if (!empty($title)) {
            $where[] = ["title","like","%$title%"];
        }
        # 通过join 、模型关联 select()指定查询的字段
        $data = Article::where($where)->join("category",'category.id','=','article.category_id')->select('article.*','category.name')->paginate(3);

        $result = [
            'data' => $data,//列表的数据
            'category' => $category,//分类数据
            'category_id' => $category_id,//搜索的分类id
            'title' => $title//搜索的分类id
        ];
        return view('admin/article-list',$result);
    }

    /**
     * 是否置顶的更新
     * 获取元素的自定义属性 data-id/data-url/data-value
     * post csrf防护（419错误码）
     * 数据表的时间戳字段
     */
    public function changeIsFirst(Request $request){
        $id = $request->post('id');
        $is_first = $request->post('status');
        $result = Article::where('id',$id)->update(['is_first' => $is_first]);
        if ($result) {
            return ['data' => $is_first,'code' => 0,'message' => '修改成功'];
        } else{
            return ['data' =>$is_first,'code' => 2001,'message' => "修改失败"];
        }

    }

    /**
     * 删除文章
     */
    public function articleDel(Request $request){
        $id = $request->post('id');
        $result = Article::destroy($id);
        if ($result) {
            return ['data' => [],'code' => 0,'message' => '删除成功'];
        } else{
            return ['data' =>[],'code' => 2001,'message' => "删除失败"];
        }
    }
}
